// ErrorBoundary.jsx
import React, { ReactNode } from 'react';

interface ErrorBoundaryProp {
  children: ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error: object | undefined;
}

class ErrorBoundary extends React.Component {
  constructor(props: ErrorBoundaryProp) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: object) {
    return { hasError: true, error };
  }

  componentDidCatch(error: object, errorInfo: object) {
    console.error('Error caught by boundary:', error, errorInfo);
  }

  render() {
    if ((this.state as ErrorBoundaryState).hasError) {
      return (
        <div className="error-fallback">
          <h2>出了点问题</h2>
          <p>应用程序遇到意外错误</p>
          <button onClick={() => this.setState({ hasError: false })}>重试</button>
        </div>
      );
    }

    return (this.props as ErrorBoundaryProp).children;
  }
}

export default ErrorBoundary;
